<?php

declare(strict_types=1);

namespace app\sys\controller;

use think\admin\Controller;
use think\admin\Exception;
use think\admin\helper\TokenHelper;
use think\admin\model\SysConfig;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 系统配置接口
 * Class Config
 * @package app\dev\controller
 */
class Config extends Controller
{
    /**
     * 获取其他配置分页列表
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function page()
    {
        $query = SysConfig::mQuery();
        $query->where(['is_deleted' => 0]);
        $query->where(['category' => 'OTHER']);
        // 数据列表搜索过滤
        $query->equal('status')->dateBetween('create_time');
        $query->like('name,code');
        $lists = $query->order('sort ASC,id ASC')->page();
    }

    /**
     * 列表获取
     * @auth true
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list()
    {
        sysoplog('系统配置', '系统配置列表获取成功');
        $this->success('获取成功！', SysConfig::mk()->where(['category' => $this->request->param('category')])->select()->toArray());
    }

    /**
     * 获取配置详情
     * @auth true
     * @return void
     */
    public function detail()
    {
        sysoplog('系统配置', '系统配置获取成功');
        $this->success('操作成功', SysConfig::detail($this->request->param('id')));
    }

    /**
     * 新增配置
     * @auth true
     * @return void
     */
    public function add()
    {
        sysoplog('系统配置', '系统配置新增成功');
        SysConfig::mForm('form');
    }

    /**
     * 更新配置按钮
     * @auth true
     * @return void
     */
    public function edit()
    {
        sysoplog('系统配置', '系统配置更新成功');
        SysConfig::mForm('form');
    }

    /**
     * 移到回收站
     * @auth true
     * @return void
     */
    public function delete()
    {
        sysoplog('系统配置', '系统配置删除成功');
        SysConfig::mSave(['is_deleted' => 1]);
    }

    /**
     * 批量更新配置
     * @return void
     * @throws Exception
     */
    public function editBatch()
    {
        $post = $this->request->post();
        // 数据数据到系统配置表
        foreach ($post as $k => $v) sysconfig($v['category'], $v['configKey'], $v['configValue']);
        sysoplog('系统配置', '系统配置批量更新');
        $this->success('保存成功！');
    }

    /**
     * 基础信息（无需权限）
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function sysBaseList()
    {
        $config = sysvar('sqm-sys-config');

        if (empty($config)) {
            $config = SysConfig::mk()->where(['category' => 'SYS_BASE'])->select()->toArray();
            sysvar('sqm-sys-config', $config);
        }

        $this->success('获取成功！', $config);
    }

}